import os.path
import sys
import time
from multiprocessing import Process
import uvicorn


from zn.common.component.component import componentManager
from zn.common.router.root import app
import zn.common.component.db
import zn.iot.terminal
import zn.iot.dtu_mb_temperature.ter_db_mb_temp


def mainFun():
    try:
        settingsPath = f"/znTer/settings"
        settingsFn = "default.json"
        args = sys.argv
        if len(args) > 1:
            settingsFn = args[1]

        settings = componentManager.settings
        settings.settingsFn = f"{settingsPath}/{settingsFn}"
        settings.load()
        rootPath = os.path.dirname(__file__)
        settings.settingsInfo['server']['rootPath'] = rootPath
        print(f"root path :{rootPath}")

        componentManager.loadComponents()

        host = settings.host
        port = settings.port

        uvicorn.run(app, host=host, port=port)
    except Exception as er:
        print(er)
def main():
    try:
        lastTime = time.time()
        p = None
        while 1>0:
            if p == None:
                p = Process(target=mainFun)
                p.daemon = True
                p.start()
                print('-------------------- start process  -------------------------')
                print(f"main process . pid:{p.pid} , startTime:{time.time()}")
                print('-------------------------------------------------------------')
            else:
                dlt = time.time() - lastTime
                if dlt >4*3600 :
                    lastTime = time.time()
                    p.terminate()
                    time.sleep(5)
                    p = None
            time.sleep(1)
    except Exception as er:
        print(er)
if __name__=="__main__":
    main()